﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CoreRp.Filters
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public class AuthRole : Attribute, IAsyncAuthorizationFilter
    {
        HashSet<string> hashRole = new HashSet<string>();
        /// <summary>
        /// 如果没有参数，则所有登陆的用户都可以访问
        /// </summary>
        public AuthRole() { }
        /// <summary>
        /// 用户拥有参数角色中任何一个角色，就可以访问被注释的接口
        /// </summary>
        /// <param name="roles">角色</param>
        public AuthRole(params E_Roles[] roles)
        {
            
            foreach(var x in roles)
            {
                hashRole.Add(x.ToString());
            }
        }


        public Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            return Task.Run(() =>
            {

                var usercode = context.HttpContext.Session.GetString("USERCODE");
                if (string.IsNullOrWhiteSpace(usercode))
                {
                    context.Result = new RedirectResult("~/admin/Login");// RedirectToPageResult("Login", new { area = "Admin/Rap" });
                }
                else
                {
                    if (hashRole.Count == 0)
                    {
                        return;
                    }
                    else
                    {
                        var userrole = context.HttpContext.Session.GetString("ROLECODE");
                        if (hashRole.Contains(userrole))
                        {
                            return;
                        }
                        else
                        {
                            context.Result = new RedirectResult("~/Err503");
                        }
                    }
                }
            });
        }
    }
}
